package project.android;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class DatabaseConnection{
	
	
	private SQLiteDatabase db = null; 
	private DbConnectionHelper helper; 
	private Context context;
	
	
	public DatabaseConnection(Context context) {
		
		this.context = context;
		
	}
	
	public void connectDatabase(String databaseName,String tableName){
	
		DbConnectionHelper.DATABASE_NAME = databaseName;
		helper = new DbConnectionHelper(context);
		db = null;
		db = helper.getWritableDatabase();
		Cursor c =db.rawQuery("SELECT * FROM sqlite_master WHERE name='"+tableName+"'",null);
		if(c.getCount() != 0){
			c = db.query(tableName, null, null, null, null, null, null);
			DbConnectionHelper.FIELDS = c.getColumnNames();
			DbConnectionHelper.TABLE_NAME = tableName; 
		}
		
	}
	
	public void close() {
		
		helper.close();
	
	}
	
	public void addTableIfNotExists( String databaseName, String tableName, String fields){
		
		String[] temp = fields.split(",");
		
		DbConnectionHelper.TABLE_NAME = tableName; 
		DbConnectionHelper.FIELDS  = new String[temp.length];
		for(int i = 0 ;i<temp.length;i++)
			DbConnectionHelper.FIELDS[i]= temp[i].split(" ")[0];
	
		db.execSQL("CREATE TABLE IF NOT EXISTS " + tableName+" ( " + fields+" ) ;");
		
	}

	public void insert(String fields){
		
			String [] input = fields.split(",");
		
			ContentValues values = createContentValues(input);
			
			db.insert(DbConnectionHelper.TABLE_NAME,null,values);
			
	}
		
	public void delete(int value){
		
		db.delete(DbConnectionHelper.TABLE_NAME,  DbConnectionHelper.FIELDS[0] + "= '" + value +"'", null);
		
	}

	public void update(int id , String values){
		
		String[] temp= values.split(",");
		ContentValues updateValues = createContentValues(temp);

		db.update(DbConnectionHelper.TABLE_NAME, updateValues, "ID" + "=" + id, null);
		
	}

	public Cursor select(String field , String value){
		
		Cursor c = db.query(true, DbConnectionHelper.TABLE_NAME, DbConnectionHelper.FIELDS,
				field + " = '" + value+"'", null, null, null, null, null);
		c.moveToFirst();
		
		return c;
		
	}

	public Cursor selectAll(){
		
		Cursor c = db.rawQuery("SELECT * FROM " + DbConnectionHelper.TABLE_NAME,null);
		
		c.moveToFirst();
		
		return c;
		
	}
	
	public void drop(){
		
		db.execSQL("DROP TABLE IF EXISTS "+DbConnectionHelper.TABLE_NAME);
		
		DbConnectionHelper.DATABASE_VERSION += 1 ;
		
	}
	
	public ContentValues createContentValues(String[] fields){
		
		ContentValues value =new ContentValues();
		
		for(int i = 0; i < fields.length; i++)
			value.put(DbConnectionHelper.FIELDS[i+1], fields[i]);
		
		return value;
		
	}
	
	
}
